﻿using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DFGK.WMS.Common.Tools
{
    public enum HttpRequestType
    {
        Get,
        Post,
        Put,
        Delete
    }
    public class ApiResponse<T>
    {
        public T Data { get; set; }
        public int Code { get; set; }
        public string Message { get; set; }
    }
    public class HttpHelpers
    {
        private readonly string _baseUrl;

        public HttpHelpers(string baseUrl)
        {
            _baseUrl = baseUrl;
        }
        /// <summary>
        /// 发送http请求
        /// </summary>
        /// <typeparam name="T">Data的类型</typeparam>
        /// <param name="requestType">枚举 访问方式 get post put delete</param>
        /// <param name="url">接口地址 会拼在baseUrl后面</param>
        /// <param name="requestData">入参 可为空 如果空传null</param>
        /// <param name="token">tokne 可为空 如果空传null</param>
        /// //返参
        /// <param name="ErrorMsg">失败原因</param>
        /// <param name="Success">请求响应失败还是成功</param>
        /// <param name="ResponseData">响应结果</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task<(string? ErrorMsg,bool Success, ApiResponse<T> ResponseData)> SendRequestAsync<T>(HttpRequestType requestType,
            string url, object? requestData, string? token)
        {
            try
            {
                string fullUrl = _baseUrl + url;

                // 创建 HttpClient 实例
                using var client = new HttpClient();

                // 添加 Authorization 请求头，携带 token
                if (!string.IsNullOrEmpty(token))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                }

                // 根据请求类型执行相应的操作
                HttpResponseMessage response;
                switch (requestType)
                {
                    case HttpRequestType.Get:
                        // 将查询参数拼接到 URL 中
                        string queryString = ToQueryString(requestData);
                        if (!string.IsNullOrEmpty(queryString))
                        {
                            fullUrl += "?" + queryString;
                        }
                        response = await client.GetAsync(fullUrl);
                        break;
                    case HttpRequestType.Post:
                        if (requestData == null)
                        {
                            response = await client.PostAsync(fullUrl, null);
                        }
                        else
                        {
                            var requestDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                            await Console.Out.WriteLineAsync(JsonConvert.SerializeObject(requestData));
                            response = await client.PostAsync(fullUrl, requestDataJson);
                        }

                        break;
                    case HttpRequestType.Put:
                        // 在实际应用中根据需要添加请求数据
                        if (requestData == null)
                        {
                            response = await client.PutAsync(fullUrl, null);
                        }
                        else
                        {
                            var putDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                            response = await client.PutAsync(fullUrl, putDataJson);
                        }
                        break;
                    case HttpRequestType.Delete:
                        // 将查询参数拼接到 URL 中
                        string deleteQueryString = ToQueryString(requestData);
                        if (!string.IsNullOrEmpty(deleteQueryString))
                        {
                            fullUrl += "?" + deleteQueryString;
                        }
                        response = await client.DeleteAsync(fullUrl);
                        break;
                    default:
                        throw new ArgumentException("Invalid request type.");
                }

                // 检查响应是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容并进行适当的转换
                    ApiResponse<T> responseData = await response.Content.ReadFromJsonAsync<ApiResponse<T>>();
                    return (null,true, responseData);
                }
                else
                {
                    // 响应失败，设置默认值并返回 false
                    return (response.ReasonPhrase, false, default);
                }
            }
            catch (Exception ex)
            {
                return ("catch:"+ex.Message ,false, default);
            }
            
        }

        public (string? ErrorMsg, bool Success, ApiResponse<T> ResponseData) SendRequest<T>(HttpRequestType requestType,
    string url, object? requestData, string? token)
        {
            try
            {
                string fullUrl = _baseUrl + url;

                // 创建 HttpClient 实例
                using var client = new HttpClient();

                // 添加 Authorization 请求头，携带 token
                if (!string.IsNullOrEmpty(token))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                }

                // 根据请求类型执行相应的操作
                HttpResponseMessage response;
                switch (requestType)
                {
                    case HttpRequestType.Get:
                        // 将查询参数拼接到 URL 中
                        string queryString = ToQueryString(requestData);
                        if (!string.IsNullOrEmpty(queryString))
                        {
                            fullUrl += "?" + queryString;
                        }
                        response = client.GetAsync(fullUrl).Result;
                        break;
                    case HttpRequestType.Post:
                        if (requestData == null)
                        {
                            response = client.PostAsync(fullUrl, null).Result;
                        }
                        else
                        {
                            var requestDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                            response = client.PostAsync(fullUrl, requestDataJson).Result;
                        }

                        break;
                    case HttpRequestType.Put:
                        // 在实际应用中根据需要添加请求数据
                        if (requestData == null)
                        {
                            response = client.PutAsync(fullUrl, null).Result;
                        }
                        else
                        {
                            var putDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                            response = client.PutAsync(fullUrl, putDataJson).Result;
                        }
                        break;
                    case HttpRequestType.Delete:
                        // 将查询参数拼接到 URL 中
                        string deleteQueryString = ToQueryString(requestData);
                        if (!string.IsNullOrEmpty(deleteQueryString))
                        {
                            fullUrl += "?" + deleteQueryString;
                        }
                        response = client.DeleteAsync(fullUrl).Result;
                        break;
                    default:
                        throw new ArgumentException("Invalid request type.");
                }

                // 检查响应是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容并进行适当的转换
                    ApiResponse<T> responseData = response.Content.ReadFromJsonAsync<ApiResponse<T>>().GetAwaiter().GetResult();
                    return (null, true, responseData);
                }
                else
                {
                    // 响应失败，设置默认值并返回 false
                    return (response.ReasonPhrase, false, default);
                }
            }
            catch (Exception ex)
            {
                return ("catch:" + ex.Message, false, default);
            }
        }


        private string ToQueryString(object requestParams)
        {
            if (requestParams == null)
            {
                return string.Empty;
            }

            var properties = from p in requestParams.GetType().GetProperties()
                             where p.GetValue(requestParams, null) != null
                             select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(requestParams, null).ToString());

            return string.Join("&", properties.ToArray());
        }
    }
}
